import React, { Component } from 'react'
import Form from './Form'
import ListItem from './ListItem'
import "./todo.css"
import "./common.scss"
import Change from './Change'
export default class Todolist extends Component {
    constructor(){
        super();
        this.state={
            keyword:'',
            showEdit:false,
            currentTodo:{},
            datalist:[
                {
                    id:1,
                    name:"beijing"
                },
                {
                    id:2,
                    name:"shanghai"
                }
            ]
        }
    }
// 添加
    handleAdd(name){
        // debugger;
        // console.log(name);
        this.state.datalist.push({
            id:new Date().getTime(),
            name:name
        })
        this.setState({})
    }
    // 查询
    handleSearch(keyword){
        this.setState({
            keyword
        })
    }
    // 删除
    handleDel(id){
        console.log(id);
        this.state.datalist.find((item,index)=>{
            if(item.id===id){
                this.state.datalist.splice(index,1);
                return true;
            }
        })
        this.setState({})
    }
    // 编辑
    handleEdit(id){
        console.log(id);
       let todo=this.state.datalist.find((item,index)=>{
            if(item.id===id){
                return true;
            }
        })
        this.setState({    
            currentTodo:todo,
            showEdit:true
        })     
    }
    // 提交
    handleSubmit=()=>{
        let txt = this.refs.name.value;
        this.state.datalist.find((item,index)=>{
            if(item.id===this.state.currentTodo.id){
                this.state.datalist[index].name=txt;
                return true;
            }
        })
        this.setState({
            showEdit:false
        })
        console.log(txt);
    }
    handleCancel=()=>{
        this.setState({
            showEdit:false
        })
    }
    render() {
        // 查询
        let list=this.state.datalist.filter((item,index)=>{
            return item.name.indexOf(this.state.keyword)>-1
        }) 
        let edit=<Change title="编辑">
            <input  type="text" ref="name" defaultValue={this.state.currentTodo.name}/>
            <button onClick={this.handleSubmit}>提交</button>
            <button onClick={this.handleCancel}>取消</button>
        </Change>;
        return (
            <div>
                <Form add={(name)=>{this.handleAdd(name)}}
                search={(name)=>{this.handleSearch(name)}}
                ></Form>
                {/* <ListItem list={this.state.datalist}></ListItem> */}
                <ListItem list={list} del={(id)=>this.handleDel(id)} edit={(id)=>this.handleEdit(id)}></ListItem>
                {
                    this.state.showEdit? edit:''
                }
                
            </div>
        )
    }
}
